package com.example.nio.nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @auther:lgb
 * @Date: 2021/5/3
 */
public class NIOTcpServer {

    private static final int PORT = 5555;
    private static ByteBuffer byteBuffer = ByteBuffer.allocate(10240);
    private static int number = 0;

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
        serverSocketChannel.configureBlocking(false);

        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("server start on port " + PORT + " ...");

        while (true) {

            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();

                if (!selectionKey.isValid())
                    continue;

                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel serverChannel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = serverChannel.accept();
                    socketChannel.configureBlocking(false);
                    SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);
                    // start the thread of writing
                    new Thread(new SendRunnable(socketChannel)).start();
                    Socket socket = socketChannel.socket();
                    System.out.println("Get a client, the remote client address: " + socket.getRemoteSocketAddress());
                } else if (selectionKey.isReadable()) {
                    // Read data from channel to buffer
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    socketChannel.socket().setReceiveBufferSize(102400);
                    String remoteAddress = socketChannel.socket().getRemoteSocketAddress().toString();

                    processByHead(socketChannel);
                }

                iterator.remove();
            }
        }
    }

    private static class SendRunnable implements Runnable {

        private SocketChannel socketChannel;

        public SendRunnable(SocketChannel socketChannel) {
            this.socketChannel = socketChannel;
        }

        public void run() {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                try {
                    String msg = bufferedReader.readLine();
                    this.socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private static void processByHead(SocketChannel socketChannel) throws IOException {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while (socketChannel.read(byteBuffer) > 0) {
            int position = byteBuffer.position();
            int limit = byteBuffer.limit();
            byteBuffer.flip();

            while (byteBuffer.remaining() > 4) {
                System.out.println("remaining :" + byteBuffer.remaining());
                System.out.println("position :" + byteBuffer.position());
                System.out.println("limit :" + byteBuffer.limit());
                // 从给定索引值(position)中,开始取出4个字节 根据字节顺序将它们组合成为一个int
                int length = byteBuffer.getInt();
                if (length != 0) {
                    System.out.println("客户端发送的长度为：" + length);
                    if (byteBuffer.remaining() < length) {
                        byteBuffer.position(position);
                        byteBuffer.limit(limit);
                        continue;
                    }

                    byte[] data = new byte[length];
                    byteBuffer.get(data, 0, length);
                    System.out.println(new String(data) + " <---> " + number++);

                } else {
                    break;
                }

            }
            // 需要变回写状态，客户端还是需要写数据的；注意，读一半数据，然后，再写数据 这时候用compact()才有意义
            byteBuffer.compact();

        }
    }


}
